package com.wg.process.controller;

import com.wg.process.core.ResultBody;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.ui.modeler.domain.AbstractModel;
import org.flowable.ui.modeler.domain.Model;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/model")
public class ModelController {


    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ModelService modelService;
    @RequestMapping(value = "/deploys/{modelid}", method = RequestMethod.GET)
    public ResultBody deplayModel(@PathVariable String modelid){
        Model modelData  = modelService.getModel(modelid);
        byte[] bytes = modelService.getBpmnXML(modelData);
        if(bytes==null){
            return ResultBody.error("模型数据为空，请先设计流程并成功保存，再进行发布。");
        }
        BpmnModel model = modelService.getBpmnModel( modelData);
        if(model.getProcesses().size()==0){
            return ResultBody.error("数据模型不符要求，请至少设计一条主线流程");
        }
            String processName = modelData.getName()+".bpmn20.xml";
        Deployment deployment1 = repositoryService.createDeployment().name(modelData.getName()).addBpmnModel(processName,model).deploy();
        return ResultBody.success(deployment1);
    }

    @RequestMapping(value = "/getmodels",method = RequestMethod.GET)
    public ResultBody getModel(){
        List<AbstractModel> modelList  =  modelService.getModelsByModelType(0);
        return ResultBody.success(modelList);
    }

}
